package com.hae.shop.micoshoppayservice.controller;

import com.hae.shop.common.base.Response;
import com.hae.shop.common.util.BeanConvertUtil;
import com.hae.shop.common.util.SnowflakeIdUtil;
import com.hae.shop.micoshoppayservice.constant.BizErrorEnum;
import com.hae.shop.micoshoppayservice.mapper.PayOrgMapper;
import com.hae.shop.micoshoppayservice.mapper.PayTransactionMapper;
import com.hae.shop.micoshoppayservice.mapper.model.PayOrgDo;
import com.hae.shop.micoshoppayservice.mapper.model.PayTransactionDo;
import com.hae.shop.micoshoppayservice.plugins.PayStrategy;
import com.hae.shop.micoshoppayservice.plugins.strategy.impl.StrategyFactory;
import com.hae.shop.micoshoppayservice.util.TokenUtil;
import com.hae.shop.pay.PayService;
import com.hae.shop.pay.model.reqDto.GetPayTokenReqDto;
import com.hae.shop.pay.model.reqDto.PayReqDto;
import com.hae.shop.pay.model.respDto.PayOrgRespDto;
import com.hae.shop.pay.model.respDto.PayTransactionRespDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 支付服务接口实现
 */
@RestController
@Validated
public class PayServiceImpl implements PayService {

    @Autowired
    private PayOrgMapper payOrgMapper;

    @Autowired
    private PayTransactionMapper payTransactionMapper;

    @Autowired
    private TokenUtil tokenUtil;

    @Override
//    @PostMapping("/getPayToken")
    public Response<String> getPayToken(@RequestBody GetPayTokenReqDto getPayTokenReqDto) {
        Response response = new Response();
        //使用雪花算法生成全局id，用于保证第三方支付接口回调结果幂等性
        String payId = Long.toString(SnowflakeIdUtil.nextId());
        //将请求信息录入数据库
        PayTransactionDo payTransactionDo = BeanConvertUtil.EToT(getPayTokenReqDto, PayTransactionDo.class);
        payTransactionDo.setPayTransId(payId);
        int insertResult = payTransactionMapper.insertPayTransactionRecord(payTransactionDo);
        //插库失败直接返回错误
        if (insertResult < 0) {
            response.setResult(BizErrorEnum.INSERT_PAY_RECORD_FAILED.getErrorCode(),
                    BizErrorEnum.INSERT_PAY_RECORD_FAILED.getErrorMsg());
            return response;
        }
        //生成支付token
        response.setResult(tokenUtil.createToken("pay_", payId));
        return response;
    }

    @Override
//    @GetMapping("/getPayOrg")
    public Response<List<PayOrgRespDto>> getPayOrg() {
        Response result = new Response();
        List<PayOrgDo> orgDoList = payOrgMapper.selectAllPayOrg();
        if (!CollectionUtils.isEmpty(orgDoList)) {
            result.setResult(BeanConvertUtil.EListToTList(orgDoList, PayOrgRespDto.class));
        } else {
            result.setResult(BizErrorEnum.NOT_RELEATIE_PAY_ORGIN.getErrorCode(),
                    BizErrorEnum.NOT_RELEATIE_PAY_ORGIN.getErrorMsg());
        }
        return result;
    }


    @Override
//    @GetMapping("/getPayTransactionByToken")
    public Response<PayTransactionRespDto> getPayTransactionByToken(@RequestParam("token") String token) {
        Response response = new Response();
        //根据支付token读取交易id
        String payTransId = tokenUtil.getToken(token);
        if (StringUtils.isEmpty(payTransId)) {
            response.setResult(BizErrorEnum.NOT_RELEVANT_PAY_ID.getErrorCode(),
                    BizErrorEnum.NOT_RELEVANT_PAY_ID.getErrorMsg());
            return response;
        }
        //根据交易id查询交易信息
        PayTransactionDo payTransactionDo = payTransactionMapper.getPayTransactionByPayTransId(payTransId);
        if (null == payTransactionDo) {
            response.setResult(BizErrorEnum.NOT_RELEVANT_PAY_RECORD.getErrorCode(),
                    BizErrorEnum.NOT_RELEVANT_PAY_RECORD.getErrorMsg());
        } else {
            response.setResult(BeanConvertUtil.EToT(payTransactionDo, PayTransactionRespDto.class));
        }
        return response;
    }

    @Override
    public Response<Boolean> payOrder(@RequestBody PayReqDto payReqDto) {
        Response<Boolean> response = new Response<>();
        //使用支付机构id查询支付机构信息
        PayOrgDo payOrgDo = payOrgMapper.selectPayOrgById(payReqDto.getPayOrgId());
        if (null == payOrgDo) {
            response.setResult(BizErrorEnum.NOT_RELEATIE_PAY_ORGIN.getErrorCode(),
                    BizErrorEnum.NOT_RELEATIE_PAY_ORGIN.getErrorMsg());
            return response;
        }
        //根据交易id查询交易信息
        Response<PayTransactionRespDto> payTransactionResponse = getPayTransactionByToken(payReqDto.getPayoken());
        if (!payTransactionResponse.isSuccess()) {
            response.setResult(payTransactionResponse.getErrorCode(), payTransactionResponse.getErrorMsg());
            return response;
        }
        //根据支付机构信息使用对应策略进行支付
        PayStrategy payStrategy = StrategyFactory.getPayStrategy(payOrgDo.getClassUrl());
        payStrategy.payOrder(payOrgDo, payTransactionResponse.getResult());
        return null;
    }
}
